package convert

import (
	"errors"
	"github.com/samber/lo"
	"k9-panel/app/model"
	dto "k9-panel/app/service/dto"
	"strings"
)

func BaseConfig2ConfigEnv(comment string, items []*model.BaseConfig) *dto.ConfigEnv {
	envItems := lo.Map(items, func(item *model.BaseConfig, _ int) *dto.ConfigEnvItem {
		return &dto.ConfigEnvItem{Key: item.Key, Value: item.Value}
	})
	return &dto.ConfigEnv{
		Comment: comment,
		Items:   envItems,
	}
}
func DerivedConfig2ConfigEnv(comment string, items []*model.DerivedConfig) *dto.ConfigEnv {
	envItems := lo.Map(items, func(item *model.DerivedConfig, _ int) *dto.ConfigEnvItem {
		return &dto.ConfigEnvItem{Key: item.Key, Value: item.Value}
	})
	return &dto.ConfigEnv{
		Comment: comment,
		Items:   envItems,
	}
}

func StringToConfigEnv(content string) (cfg *dto.ConfigEnv, er error) {
	cfg = &dto.ConfigEnv{}
	cfg.Comment = ""
	configs := strings.Split(strings.TrimSpace(content), "\n")

	for idx, config := range configs {
		config := strings.TrimSpace(config)
		if strings.HasPrefix(config, "##") {
			continue
		}
		if len(config) == 0 {
			continue
		}
		if strings.HasPrefix(config, "#") && !strings.Contains(config, "##") && !strings.Contains(config, "=") {
			config += "=1"
		}
		configPair := strings.Split(config, "=")
		if len(configPair) < 2 {
			return nil, errors.New("配置格式异常,附近位置:" + config)
		}
		baseConfig := &dto.ConfigEnvItem{}
		baseConfig.Key = configPair[0]
		baseConfig.Value = strings.Join(configPair[1:], "=")
		baseConfig.Sort = idx
		cfg.Items = append(cfg.Items, baseConfig)
	}
	return cfg, nil
}
